package uk.co.agileworks.bidpirate.service;

import java.math.BigInteger;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Encryptor {

	private static final String ALGORITHM = "AES";
	private static final int RADIX = 16;

	private final String key;

	public Encryptor(String key) {
		this.key = key;
	}

	public String decrypt(String text) {
		SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			return new String(cipher.doFinal(fromHex(text)));
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}

	public String encrypt(String text) {
		SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);
			return toHex(cipher.doFinal(text.getBytes()));
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}

	private byte[] fromHex(String hex) {
		return new BigInteger(hex, RADIX).toByteArray();
	}

	private String toHex(byte[] bytes) {
		return new BigInteger(bytes).toString(RADIX);
	}
	

}
